package com.zoe.onelink.util;

import cn.hutool.core.net.NetUtil;

import javax.servlet.http.HttpServletRequest;
import java.net.URL;

/**
 * <p>标题: IP工具类</p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-10-16
 */
public class IpUtil extends NetUtil {

    private static final String UNKNOWN = "unknown";
    public static final String[] IP_HEADER_NAMES = {"clientIp", "x-forwarded-for", "Proxy-Client-IP",
            "WL-Proxy-Client-IP", "X-Real-IP"};

    /**
     * 客户端真实IP地址的
     */
    public static String getIpAddr(HttpServletRequest request) {
        for (String ipHeaderName : IP_HEADER_NAMES) {
            String ip = request.getHeader(ipHeaderName);
            if (StrUtil.isNotBlank(ip) || !UNKNOWN.equals(ip)) {
                return ip;
            }
        }
        return request.getRemoteAddr();
    }

    /**
     * 提取URL中的IP和端口
     */
    public static String parseIpAndPort(String url) {
        try {
            URL urlObj = new URL(url);
            return urlObj.getAuthority();
        } catch (Exception e) {
            return null;
        }
    }

}
